<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="rule-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="规则名称" prop="ruleName">
            <el-input
              v-model="form.ruleName"
              placeholder="请输入规则名称"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规则类型" prop="ruleType">
            <el-select v-model="form.ruleType" placeholder="请选择规则类型" style="width: 100%">
              <el-option label="设备规则" value="device" />
              <el-option label="数据规则" value="data" />
              <el-option label="告警规则" value="alarm" />
              <el-option label="场景规则" value="scene" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="优先级" prop="priority">
            <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 100%">
              <el-option label="高" value="high" />
              <el-option label="中" value="medium" />
              <el-option label="低" value="low" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规则状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="规则描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入规则描述"
        />
      </el-form-item>

      <el-form-item label="触发条件" prop="condition">
        <div class="condition-editor">
          <el-tabs v-model="conditionTab" type="card">
            <el-tab-pane label="可视化编辑" name="visual">
              <div class="visual-condition">
                <div class="condition-row" v-for="(condition, index) in visualConditions" :key="index">
                  <div class="condition-fields">
                    <el-select v-model="condition.field" placeholder="选择字段" class="field-select">
                      <el-option-group label="水位监测">
                        <el-option label="库水位" value="reservoirLevel" />
                        <el-option label="入库水位" value="inflowLevel" />
                        <el-option label="出库水位" value="outflowLevel" />
                        <el-option label="汛限水位" value="floodControlLevel" />
                        <el-option label="死水位" value="deadLevel" />
                      </el-option-group>
                      <el-option-group label="流量监测">
                        <el-option label="入库流量" value="inflowRate" />
                        <el-option label="出库流量" value="outflowRate" />
                        <el-option label="泄洪流量" value="spillwayFlow" />
                        <el-option label="发电流量" value="powerFlow" />
                      </el-option-group>
                      <el-option-group label="水量监测">
                        <el-option label="库容量" value="reservoirCapacity" />
                        <el-option label="有效库容" value="activeCapacity" />
                        <el-option label="蓄水量" value="waterStorage" />
                      </el-option-group>
                      <el-option-group label="水质监测">
                        <el-option label="水温" value="waterTemperature" />
                        <el-option label="pH值" value="pH" />
                        <el-option label="溶解氧" value="dissolvedOxygen" />
                        <el-option label="浊度" value="turbidity" />
                        <el-option label="电导率" value="conductivity" />
                        <el-option label="COD" value="cod" />
                        <el-option label="氨氮" value="ammoniaNitrogen" />
                        <el-option label="总磷" value="totalPhosphorus" />
                        <el-option label="总氮" value="totalNitrogen" />
                      </el-option-group>
                      <el-option-group label="气象监测">
                        <el-option label="气温" value="airTemperature" />
                        <el-option label="湿度" value="humidity" />
                        <el-option label="气压" value="pressure" />
                        <el-option label="风速" value="windSpeed" />
                        <el-option label="风向" value="windDirection" />
                        <el-option label="降雨量" value="rainfall" />
                        <el-option label="降雨强度" value="rainfallIntensity" />
                        <el-option label="蒸发量" value="evaporation" />
                      </el-option-group>
                      <el-option-group label="大坝安全">
                        <el-option label="水平位移" value="horizontalDisplacement" />
                        <el-option label="垂直位移" value="verticalDisplacement" />
                        <el-option label="倾斜度" value="inclination" />
                        <el-option label="渗透压力" value="seepagePressure" />
                        <el-option label="渗流量" value="seepageFlow" />
                        <el-option label="扬压力" value="upliftPressure" />
                      </el-option-group>
                      <el-option-group label="设备运行">
                        <el-option label="发电功率" value="generatorPower" />
                        <el-option label="设备转速" value="rotationSpeed" />
                        <el-option label="设备振动" value="vibration" />
                        <el-option label="设备温度" value="equipmentTemperature" />
                        <el-option label="闸门开度" value="gateOpening" />
                        <el-option label="启闭力" value="operatingForce" />
                        <el-option label="泵站流量" value="pumpFlow" />
                        <el-option label="泵站扬程" value="pumpHead" />
                        <el-option label="设备状态" value="deviceStatus" />
                      </el-option-group>
                      <el-option-group label="系统监测">
                        <el-option label="数据值" value="dataValue" />
                        <el-option label="时间戳" value="timestamp" />
                        <el-option label="报警级别" value="alarmLevel" />
                      </el-option-group>
                    </el-select>
                    <el-select v-model="condition.operator" placeholder="操作符" class="operator-select">
                      <el-option label="等于" value="=" />
                      <el-option label="不等于" value="!=" />
                      <el-option label="大于" value=">" />
                      <el-option label="小于" value="<" />
                      <el-option label="大于等于" value=">=" />
                      <el-option label="小于等于" value="<=" />
                      <el-option label="包含" value="contains" />
                    </el-select>
                    <el-input v-model="condition.value" placeholder="值" class="value-input" />
                    <el-select 
                      v-model="condition.logic" 
                      placeholder="逻辑" 
                      class="logic-select"
                      v-if="index < visualConditions.length - 1"
                    >
                      <el-option label="AND" value="AND" />
                      <el-option label="OR" value="OR" />
                    </el-select>
                  </div>
                  <div class="condition-actions">
                    <el-button 
                      type="primary" 
                      icon="Plus" 
                      size="small" 
                      @click="addCondition" 
                      v-if="index === visualConditions.length - 1"
                    >
                      添加
                    </el-button>
                    <el-button 
                      type="danger" 
                      icon="Delete" 
                      size="small" 
                      @click="removeCondition(index)" 
                      v-if="visualConditions.length > 1"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="代码编辑" name="code">
              <el-input
                v-model="form.condition"
                type="textarea"
                :rows="4"
                placeholder="请输入触发条件表达式，例如：temperature > 80 AND humidity < 30"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-form-item>

      <el-form-item label="执行动作" prop="action">
        <div class="action-editor">
          <el-tabs v-model="actionTab" type="card">
            <el-tab-pane label="可视化编辑" name="visual">
              <div class="visual-action">
                <div class="action-row" v-for="(action, index) in visualActions" :key="index">
                  <div class="action-fields">
                    <el-select v-model="action.type" placeholder="动作类型" class="type-select" @change="handleActionTypeChange(index)">
                       <el-option label="发送通知" value="notification" />
                       <el-option label="控制设备" value="deviceControl" />
                       <el-option label="记录日志" value="log" />
                       <el-option label="调用接口" value="api" />
                       <el-option label="发送邮件" value="email" />
                     </el-select>
                     <el-select 
                       v-model="action.target" 
                       placeholder="选择目标对象" 
                       class="target-select"
                       @change="handleTargetChange(index)"
                     >
                       <el-option 
                         v-for="target in getActionTargets(action.type)" 
                         :key="target.value" 
                         :label="target.label" 
                         :value="target.value"
                       />
                     </el-select>
                     <el-select 
                       v-model="action.params" 
                       placeholder="选择操作参数" 
                       class="params-select"
                       v-if="action.target && getActionParams(action.type, action.target).length > 0"
                     >
                       <el-option 
                         v-for="param in getActionParams(action.type, action.target)" 
                         :key="param.value" 
                         :label="param.label" 
                         :value="param.value"
                       />
                     </el-select>
                     <el-input 
                       v-else-if="!action.target || getActionParams(action.type, action.target).length === 0"
                       v-model="action.params" 
                       placeholder="参数" 
                       class="params-input" 
                     />
                  </div>
                  <div class="action-actions">
                    <el-button 
                      type="primary" 
                      icon="Plus" 
                      size="small" 
                      @click="addAction" 
                      v-if="index === visualActions.length - 1"
                    >
                      添加
                    </el-button>
                    <el-button 
                      type="danger" 
                      icon="Delete" 
                      size="small" 
                      @click="removeAction(index)" 
                      v-if="visualActions.length > 1"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="代码编辑" name="code">
              <el-input
                v-model="form.action"
                type="textarea"
                :rows="4"
                placeholder="请输入执行动作，例如：sendNotification('温度异常告警', '设备温度超过阈值')"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-form-item>

      <el-form-item label="高级设置">
        <div class="advanced-settings">
          <el-collapse v-model="activeCollapse">
            <el-collapse-item title="执行设置" name="execution">
              <div class="settings-row">
                <div class="settings-fields">
                  <el-form-item label="执行频率" class="inline-form-item">
                    <el-select v-model="form.executionFrequency" placeholder="选择执行频率" class="frequency-select">
                      <el-option label="立即执行" value="immediate" />
                      <el-option label="延迟执行" value="delayed" />
                      <el-option label="定时执行" value="scheduled" />
                      <el-option label="批量执行" value="batch" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="延迟时间(秒)" v-if="form.executionFrequency === 'delayed'" class="inline-form-item">
                    <el-input-number v-model="form.delayTime" :min="1" :max="3600" class="delay-input" />
                  </el-form-item>
                  <el-form-item label="最大重试次数" class="inline-form-item">
                    <el-input-number v-model="form.maxRetries" :min="0" :max="10" class="retry-input" />
                  </el-form-item>
                </div>
              </div>
            </el-collapse-item>
            <el-collapse-item title="触发设置" name="trigger">
              <div class="settings-row">
                <div class="settings-fields">
                  <el-form-item label="触发模式" class="inline-form-item">
                    <el-select v-model="form.triggerMode" placeholder="选择触发模式" class="mode-select">
                      <el-option label="实时触发" value="realtime" />
                      <el-option label="批量触发" value="batch" />
                      <el-option label="定时触发" value="scheduled" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="冷却时间(秒)" class="inline-form-item">
                    <el-input-number v-model="form.cooldownTime" :min="0" :max="86400" class="cooldown-input" />
                  </el-form-item>
                  <el-form-item label="最大触发次数" class="inline-form-item">
                    <el-input-number v-model="form.maxTriggers" :min="0" class="max-triggers-input" />
                  </el-form-item>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'

// Props
interface Props {
  visible: boolean
  title: string
  formData: any
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  title: '新增规则',
  formData: () => ({})
})

// Emits
const emit = defineEmits(['update:visible', 'submit'])

// 响应式数据
const formRef = ref()
const submitting = ref(false)
const conditionTab = ref('visual')
const actionTab = ref('visual')
const activeCollapse = ref(['execution', 'trigger'])

// 表单数据
const form = reactive({
  ruleId: '',
  ruleName: '',
  ruleType: '',
  priority: 'medium',
  status: 1,
  description: '',
  condition: '',
  action: '',
  executionFrequency: 'immediate',
  delayTime: 0,
  maxRetries: 3,
  triggerMode: 'realtime',
  cooldownTime: 0,
  maxTriggers: 0
})

// 可视化条件
const visualConditions = ref([
  { field: '', operator: '', value: '', logic: 'AND' }
])

// 可视化动作
const visualActions = ref([
  { type: '', target: '', params: '' }
])

// 水库设备类型和参数配置
const deviceTypes = ref([
  {
    label: '闸门设备',
    value: 'gate',
    icon: 'gate',
    params: [
      { label: '完全开启', value: 'open_100' },
      { label: '开启75%', value: 'open_75' },
      { label: '开启50%', value: 'open_50' },
      { label: '开启25%', value: 'open_25' },
      { label: '完全关闭', value: 'close_0' },
      { label: '紧急关闭', value: 'emergency_close' }
    ]
  },
  {
    label: '泵站设备',
    value: 'pump',
    icon: 'pump',
    params: [
      { label: '启动泵站', value: 'start_pump' },
      { label: '停止泵站', value: 'stop_pump' },
      { label: '调节流量至最大', value: 'max_flow' },
      { label: '调节流量至75%', value: 'flow_75' },
      { label: '调节流量至50%', value: 'flow_50' },
      { label: '调节流量至25%', value: 'flow_25' },
      { label: '紧急停机', value: 'emergency_stop' }
    ]
  },
  {
    label: '阀门设备',
    value: 'valve',
    icon: 'valve',
    params: [
      { label: '开启阀门', value: 'valve_open' },
      { label: '关闭阀门', value: 'valve_close' },
      { label: '开启50%', value: 'valve_half_open' },
      { label: '调节至安全位置', value: 'valve_safe_position' },
      { label: '紧急切断', value: 'valve_emergency_cut' }
    ]
  },
  {
    label: '报警设备',
    value: 'alarm',
    icon: 'alarm',
    params: [
      { label: '发送一级报警', value: 'alarm_level_1' },
      { label: '发送二级报警', value: 'alarm_level_2' },
      { label: '发送三级报警', value: 'alarm_level_3' },
      { label: '发送紧急报警', value: 'alarm_emergency' },
      { label: '取消报警', value: 'alarm_cancel' },
      { label: '报警确认', value: 'alarm_confirm' }
    ]
  },
  {
    label: '监控设备',
    value: 'monitor',
    icon: 'monitor',
    params: [
      { label: '开始录像', value: 'start_recording' },
      { label: '停止录像', value: 'stop_recording' },
      { label: '拍照存档', value: 'take_snapshot' },
      { label: '调整监控角度', value: 'adjust_angle' },
      { label: '夜视模式', value: 'night_vision' },
      { label: '重置监控位置', value: 'reset_position' }
    ]
  },
  {
    label: '发电设备',
    value: 'generator',
    icon: 'generator',
    params: [
      { label: '启动发电机', value: 'start_generator' },
      { label: '停止发电机', value: 'stop_generator' },
      { label: '调节功率至最大', value: 'max_power' },
      { label: '调节功率至75%', value: 'power_75' },
      { label: '调节功率至50%', value: 'power_50' },
      { label: '调节功率至25%', value: 'power_25' },
      { label: '紧急停机', value: 'emergency_shutdown' }
    ]
  },
  {
    label: '照明设备',
    value: 'lighting',
    icon: 'lighting',
    params: [
      { label: '开启照明', value: 'turn_on' },
      { label: '关闭照明', value: 'turn_off' },
      { label: '调节亮度至100%', value: 'brightness_100' },
      { label: '调节亮度至75%', value: 'brightness_75' },
      { label: '调节亮度至50%', value: 'brightness_50' },
      { label: '调节亮度至25%', value: 'brightness_25' },
      { label: '应急照明', value: 'emergency_lighting' }
    ]
  },
  {
    label: '通信设备',
    value: 'communication',
    icon: 'communication',
    params: [
      { label: '发送短信通知', value: 'send_sms' },
      { label: '拨打电话', value: 'make_call' },
      { label: '发送邮件', value: 'send_email' },
      { label: '广播通知', value: 'broadcast' },
      { label: '启动应急通信', value: 'emergency_comm' }
    ]
  }
])

// 根据设备类型获取参数选项
const getDeviceParams = (deviceType: string) => {
  const device = deviceTypes.value.find(d => d.value === deviceType)
  return device ? device.params : []
}

// 所有动作类型的联动数据
const actionTargets = ref({
  // 发送通知的目标对象
  notification: [
    { label: '系统管理员', value: 'admin' },
    { label: '值班人员', value: 'operator' },
    { label: '维护人员', value: 'maintenance' },
    { label: '安全负责人', value: 'security' },
    { label: '技术支持', value: 'support' },
    { label: '应急响应组', value: 'emergency' }
  ],
  
  // 控制设备的目标对象（已有的设备类型）
  deviceControl: [
    { label: '闸门设备', value: 'gate' },
    { label: '泵站设备', value: 'pump' },
    { label: '阀门设备', value: 'valve' },
    { label: '报警设备', value: 'alarm' },
    { label: '监控设备', value: 'monitor' },
    { label: '发电设备', value: 'generator' },
    { label: '照明设备', value: 'lighting' },
    { label: '通信设备', value: 'communication' }
  ],
  
  // 记录日志的目标对象
  log: [
    { label: '系统日志', value: 'system' },
    { label: '操作日志', value: 'operation' },
    { label: '安全日志', value: 'security' },
    { label: '设备日志', value: 'device' },
    { label: '报警日志', value: 'alarm' },
    { label: '维护日志', value: 'maintenance' }
  ],
  
  // 调用接口的目标对象
  api: [
    { label: '设备管理系统', value: 'device_management' },
    { label: '数据分析平台', value: 'data_platform' },
    { label: '报警中心', value: 'alarm_center' },
    { label: '维护管理系统', value: 'maintenance_system' },
    { label: '应急指挥系统', value: 'emergency_system' },
    { label: '数据备份服务', value: 'backup_service' }
  ],
  
  // 发送邮件的目标对象
  email: [
    { label: '管理层邮件组', value: 'management_group' },
    { label: '技术团队邮件组', value: 'tech_group' },
    { label: '运维团队邮件组', value: 'ops_group' },
    { label: '安全团队邮件组', value: 'security_group' },
    { label: '应急响应邮件组', value: 'emergency_group' },
    { label: '外部合作方', value: 'external_partners' }
  ]
})

// 所有动作类型的参数选项
const actionParams = ref({
  // 发送通知的参数
  notification: {
    admin: [
      { label: '高优先级通知', value: 'high_priority' },
      { label: '普通通知', value: 'normal' },
      { label: '系统状态通知', value: 'system_status' },
      { label: '设备异常通知', value: 'device_error' }
    ],
    operator: [
      { label: '值班提醒', value: 'duty_reminder' },
      { label: '操作指令', value: 'operation_command' },
      { label: '设备状态更新', value: 'device_update' },
      { label: '紧急处理通知', value: 'emergency_notice' }
    ],
    maintenance: [
      { label: '维护提醒', value: 'maintenance_reminder' },
      { label: '设备检修通知', value: 'repair_notice' },
      { label: '备件更换提醒', value: 'parts_replacement' },
      { label: '定期保养通知', value: 'routine_maintenance' }
    ],
    security: [
      { label: '安全警报', value: 'security_alert' },
      { label: '入侵检测', value: 'intrusion_detection' },
      { label: '权限变更通知', value: 'permission_change' },
      { label: '安全审计提醒', value: 'security_audit' }
    ],
    support: [
      { label: '技术支持请求', value: 'support_request' },
      { label: '故障报告', value: 'fault_report' },
      { label: '系统升级通知', value: 'upgrade_notice' },
      { label: '配置变更通知', value: 'config_change' }
    ],
    emergency: [
      { label: '紧急响应启动', value: 'emergency_start' },
      { label: '灾害预警', value: 'disaster_warning' },
      { label: '应急疏散通知', value: 'evacuation_notice' },
      { label: '救援协调通知', value: 'rescue_coordination' }
    ]
  },
  
  // 控制设备的参数（已有的设备参数）
  deviceControl: {
    gate: [
      { label: '完全开启', value: 'fully_open' },
      { label: '开启75%', value: 'open_75' },
      { label: '开启50%', value: 'open_50' },
      { label: '开启25%', value: 'open_25' },
      { label: '完全关闭', value: 'fully_close' },
      { label: '紧急关闭', value: 'emergency_close' }
    ],
    pump: [
      { label: '启动泵站', value: 'start_pump' },
      { label: '停止泵站', value: 'stop_pump' },
      { label: '调节流量至最大', value: 'max_flow' },
      { label: '调节流量至50%', value: 'half_flow' },
      { label: '紧急停机', value: 'emergency_stop' }
    ],
    valve: [
      { label: '开启阀门', value: 'open_valve' },
      { label: '关闭阀门', value: 'close_valve' },
      { label: '开启50%', value: 'half_open' },
      { label: '调节至安全位置', value: 'safe_position' },
      { label: '紧急切断', value: 'emergency_cutoff' }
    ],
    alarm: [
      { label: '发送一级报警', value: 'level_1_alarm' },
      { label: '发送二级报警', value: 'level_2_alarm' },
      { label: '发送三级报警', value: 'level_3_alarm' },
      { label: '取消报警', value: 'cancel_alarm' },
      { label: '报警确认', value: 'acknowledge_alarm' }
    ],
    monitor: [
      { label: '开始录像', value: 'start_recording' },
      { label: '停止录像', value: 'stop_recording' },
      { label: '拍照存档', value: 'take_snapshot' },
      { label: '调整至预设位置1', value: 'preset_1' },
      { label: '调整至预设位置2', value: 'preset_2' },
      { label: '开启夜视模式', value: 'night_vision' }
    ],
    generator: [
      { label: '启动发电机', value: 'start_generator' },
      { label: '停止发电机', value: 'stop_generator' },
      { label: '调节功率至最大', value: 'max_power' },
      { label: '调节功率至50%', value: 'half_power' },
      { label: '紧急停机', value: 'emergency_shutdown' }
    ],
    lighting: [
      { label: '开启照明', value: 'turn_on' },
      { label: '关闭照明', value: 'turn_off' },
      { label: '调节亮度至100%', value: 'brightness_100' },
      { label: '调节亮度至75%', value: 'brightness_75' },
      { label: '调节亮度至50%', value: 'brightness_50' },
      { label: '调节亮度至25%', value: 'brightness_25' },
      { label: '应急照明', value: 'emergency_lighting' }
    ],
    communication: [
      { label: '发送短信通知', value: 'send_sms' },
      { label: '发送邮件通知', value: 'send_email' },
      { label: '拨打电话', value: 'make_call' },
      { label: '广播通知', value: 'broadcast' },
      { label: '启动应急通信', value: 'emergency_comm' }
    ]
  },
  
  // 记录日志的参数
  log: {
    system: [
      { label: '记录系统启动', value: 'system_start' },
      { label: '记录系统关闭', value: 'system_shutdown' },
      { label: '记录配置变更', value: 'config_change' },
      { label: '记录性能指标', value: 'performance_metrics' }
    ],
    operation: [
      { label: '记录用户操作', value: 'user_operation' },
      { label: '记录设备操作', value: 'device_operation' },
      { label: '记录规则触发', value: 'rule_trigger' },
      { label: '记录异常操作', value: 'abnormal_operation' }
    ],
    security: [
      { label: '记录登录事件', value: 'login_event' },
      { label: '记录权限变更', value: 'permission_change' },
      { label: '记录安全事件', value: 'security_event' },
      { label: '记录访问控制', value: 'access_control' }
    ],
    device: [
      { label: '记录设备状态', value: 'device_status' },
      { label: '记录设备故障', value: 'device_fault' },
      { label: '记录维护记录', value: 'maintenance_record' },
      { label: '记录性能数据', value: 'performance_data' }
    ],
    alarm: [
      { label: '记录报警触发', value: 'alarm_trigger' },
      { label: '记录报警处理', value: 'alarm_handling' },
      { label: '记录报警确认', value: 'alarm_acknowledge' },
      { label: '记录报警统计', value: 'alarm_statistics' }
    ],
    maintenance: [
      { label: '记录维护计划', value: 'maintenance_plan' },
      { label: '记录维护执行', value: 'maintenance_execution' },
      { label: '记录备件使用', value: 'parts_usage' },
      { label: '记录维护成本', value: 'maintenance_cost' }
    ]
  },
  
  // 调用接口的参数
  api: {
    device_management: [
      { label: '同步设备状态', value: 'sync_device_status' },
      { label: '更新设备配置', value: 'update_device_config' },
      { label: '获取设备信息', value: 'get_device_info' },
      { label: '控制设备操作', value: 'control_device' }
    ],
    data_platform: [
      { label: '提交分析数据', value: 'submit_analysis_data' },
      { label: '获取分析报告', value: 'get_analysis_report' },
      { label: '更新分析模型', value: 'update_analysis_model' },
      { label: '触发数据分析', value: 'trigger_analysis' }
    ],
    alarm_center: [
      { label: '发送报警信息', value: 'send_alarm_info' },
      { label: '更新报警状态', value: 'update_alarm_status' },
      { label: '获取处理指令', value: 'get_handling_instruction' },
      { label: '确认报警处理', value: 'confirm_alarm_handling' }
    ],
    maintenance_system: [
      { label: '创建维护工单', value: 'create_maintenance_order' },
      { label: '更新维护状态', value: 'update_maintenance_status' },
      { label: '获取维护计划', value: 'get_maintenance_plan' },
      { label: '提交维护报告', value: 'submit_maintenance_report' }
    ],
    emergency_system: [
      { label: '启动应急预案', value: 'start_emergency_plan' },
      { label: '更新应急状态', value: 'update_emergency_status' },
      { label: '获取应急指令', value: 'get_emergency_instruction' },
      { label: '上报应急情况', value: 'report_emergency_situation' }
    ],
    backup_service: [
      { label: '触发数据备份', value: 'trigger_data_backup' },
      { label: '验证备份完整性', value: 'verify_backup_integrity' },
      { label: '恢复备份数据', value: 'restore_backup_data' },
      { label: '清理过期备份', value: 'cleanup_expired_backup' }
    ]
  },
  
  // 发送邮件的参数
  email: {
    management_group: [
      { label: '发送状态报告', value: 'status_report' },
      { label: '发送异常通知', value: 'exception_notice' },
      { label: '发送决策建议', value: 'decision_suggestion' },
      { label: '发送月度总结', value: 'monthly_summary' }
    ],
    tech_group: [
      { label: '发送技术警报', value: 'technical_alert' },
      { label: '发送系统更新通知', value: 'system_update_notice' },
      { label: '发送故障报告', value: 'fault_report' },
      { label: '发送性能分析', value: 'performance_analysis' }
    ],
    ops_group: [
      { label: '发送运维提醒', value: 'ops_reminder' },
      { label: '发送巡检通知', value: 'inspection_notice' },
      { label: '发送值班安排', value: 'duty_schedule' },
      { label: '发送操作指南', value: 'operation_guide' }
    ],
    security_group: [
      { label: '发送安全警报', value: 'security_alert' },
      { label: '发送威胁通知', value: 'threat_notice' },
      { label: '发送安全审计', value: 'security_audit' },
      { label: '发送合规报告', value: 'compliance_report' }
    ],
    emergency_group: [
      { label: '发送紧急通知', value: 'emergency_notice' },
      { label: '发送应急指令', value: 'emergency_instruction' },
      { label: '发送疏散通知', value: 'evacuation_notice' },
      { label: '发送救援协调', value: 'rescue_coordination' }
    ],
    external_partners: [
      { label: '发送合作通知', value: 'cooperation_notice' },
      { label: '发送数据共享', value: 'data_sharing' },
      { label: '发送服务报告', value: 'service_report' },
      { label: '发送协调请求', value: 'coordination_request' }
    ]
  }
})

// 获取动作类型对应的目标对象选项
const getActionTargets = (actionType: string) => {
  return actionTargets.value[actionType] || []
}

// 获取动作类型和目标对象对应的参数选项
const getActionParams = (actionType: string, target: string) => {
  const typeParams = actionParams.value[actionType]
  if (!typeParams || !target) return []
  return typeParams[target] || []
}

// 监听设备类型变化，重置参数
const handleDeviceTypeChange = (actionIndex: number) => {
  visualActions.value[actionIndex].params = ''
}

// 监听动作类型变化，重置目标对象和参数
const handleActionTypeChange = (actionIndex: number) => {
  visualActions.value[actionIndex].target = ''
  visualActions.value[actionIndex].params = ''
}

// 监听目标对象变化，重置参数
const handleActionTargetChange = (actionIndex: number) => {
  visualActions.value[actionIndex].params = ''
}

// 表单验证规则
const rules = {
  ruleName: [
    { required: true, message: '请输入规则名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  ruleType: [
    { required: true, message: '请选择规则类型', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  condition: [
    { required: true, message: '请输入触发条件', trigger: 'blur' }
  ],
  action: [
    { required: true, message: '请输入执行动作', trigger: 'blur' }
  ]
}

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 监听可视化条件变化
watch(visualConditions, () => {
  updateConditionFromVisual()
}, { deep: true })

// 监听可视化动作变化
watch(visualActions, () => {
  updateActionFromVisual()
}, { deep: true })

// 重置表单数据
const resetFormData = () => {
  Object.assign(form, {
    ruleId: '',
    ruleName: '',
    ruleType: '',
    priority: 'medium',
    status: 1,
    description: '',
    condition: '',
    action: '',
    executionFrequency: 'immediate',
    delayTime: 0,
    maxRetries: 3,
    triggerMode: 'realtime',
    cooldownTime: 0,
    maxTriggers: 0
  })
  resetVisualData()
}

// 重置可视化数据
const resetVisualData = () => {
  visualConditions.value = [
    { field: '', operator: '', value: '', logic: 'AND' }
  ]
  visualActions.value = [
    { type: '', target: '', params: '' }
  ]
}

// 解析现有条件数据（用于编辑回显）
const parseExistingConditions = (conditionStr: string) => {
  if (!conditionStr) {
    resetVisualData()
    return
  }
  
  try {
    // 简单的条件解析逻辑
    const conditions = []
    const parts = conditionStr.split(/\s+(AND|OR)\s+/)
    
    for (let i = 0; i < parts.length; i += 2) {
      const part = parts[i].trim()
      if (part) {
        // 解析单个条件，例如: "temperature > 30"
        const match = part.match(/(\w+)\s*([><=!]+)\s*(.+)/)
        if (match) {
          conditions.push({
            field: match[1],
            operator: match[2],
            value: match[3],
            logic: i + 1 < parts.length ? parts[i + 1] : 'AND'
          })
        }
      }
    }
    
    if (conditions.length > 0) {
      visualConditions.value = conditions
    } else {
      resetVisualData()
    }
  } catch (error) {
    console.warn('解析条件数据失败:', error)
    resetVisualData()
  }
}

// 解析现有动作数据（用于编辑回显）
const parseExistingActions = (actionStr: string) => {
  if (!actionStr) {
    visualActions.value = [{ type: '', target: '', params: '' }]
    return
  }
  
  try {
    // 简单的动作解析逻辑
    const actions = []
    const actionParts = actionStr.split(';').filter(part => part.trim())
    
    actionParts.forEach(part => {
      const trimmed = part.trim()
      if (trimmed) {
        // 解析动作，例如: "sendEmail(admin@example.com)"
        const match = trimmed.match(/(\w+)\(([^)]*)\)/)
        if (match) {
          actions.push({
            type: match[1],
            target: 'system', // 默认目标
            params: match[2]
          })
        } else {
          // 简单动作格式
          actions.push({
            type: trimmed,
            target: '',
            params: ''
          })
        }
      }
    })
    
    if (actions.length > 0) {
      visualActions.value = actions
    } else {
      visualActions.value = [{ type: '', target: '', params: '' }]
    }
  } catch (error) {
    console.warn('解析动作数据失败:', error)
    visualActions.value = [{ type: '', target: '', params: '' }]
  }
}

// 监听表单数据变化
watch(() => props.formData, (newData) => {
  if (newData) {
    // 重置表单数据
    Object.assign(form, {
      ruleId: '',
      ruleName: '',
      ruleType: '',
      priority: 'medium',
      status: 1,
      description: '',
      condition: '',
      action: '',
      executionFrequency: 'immediate',
      delayTime: 0,
      maxRetries: 3,
      triggerMode: 'realtime',
      cooldownTime: 0,
      maxTriggers: 0,
      ...newData
    })
    
    // 处理编辑模式的数据回显
    if (newData.ruleId) {
      // 编辑模式：解析现有的条件和动作数据
      parseExistingConditions(newData.condition || '')
      parseExistingActions(newData.action || '')
    } else {
      // 新增模式：重置可视化数据
      resetVisualData()
    }
  } else {
    // 如果没有传入数据，重置所有数据
    resetFormData()
  }
}, { deep: true, immediate: true })

// 监听可视化条件变化
watch(visualConditions, () => {
  updateConditionFromVisual()
}, { deep: true })

// 监听可视化动作变化
watch(visualActions, () => {
  updateActionFromVisual()
}, { deep: true })

// 方法
const addCondition = () => {
  visualConditions.value.push({ field: '', operator: '', value: '', logic: 'AND' })
}

const removeCondition = (index: number) => {
  visualConditions.value.splice(index, 1)
}

const addAction = () => {
  visualActions.value.push({ type: '', target: '', params: '' })
}

const removeAction = (index: number) => {
  visualActions.value.splice(index, 1)
}

// 处理目标对象变化，清理下级数据
const handleTargetChange = (index: number) => {
  // 当目标对象改变时，清空参数选择
  if (visualActions.value[index]) {
    visualActions.value[index].params = ''
  }
}

const updateConditionFromVisual = () => {
  if (conditionTab.value === 'visual') {
    const conditions = visualConditions.value
      .filter(c => c.field && c.operator && c.value)
      .map((c, index) => {
        const condition = `${c.field} ${c.operator} ${c.value}`
        return index < visualConditions.value.length - 1 ? `${condition} ${c.logic}` : condition
      })
    form.condition = conditions.join(' ')
  }
}

const updateActionFromVisual = () => {
  if (actionTab.value === 'visual') {
    const actions = visualActions.value
      .filter(a => a.type && a.target)
      .map(a => `${a.type}('${a.target}'${a.params ? `, '${a.params}'` : ''})`)
    form.action = actions.join('; ')
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 生成规则ID（如果是新增）
    if (!form.ruleId) {
      form.ruleId = 'R' + Date.now().toString().slice(-6)
    }
    
    emit('submit', { ...form })
  } catch (error) {
    ElMessage.error('请检查表单填写是否正确')
  } finally {
    submitting.value = false
  }
}

const handleClose = () => {
  formRef.value?.resetFields()
  visualConditions.value = [{ field: '', operator: '', value: '', logic: 'AND' }]
  visualActions.value = [{ type: '', target: '', params: '' }]
  emit('update:visible', false)
}
</script>

<style scoped>
.rule-form-dialog {
  .el-form {
    padding: 20px;
  }
  
  .el-form-item {
    margin-bottom: 20px;
  }
  
  .condition-editor, .action-editor, .advanced-settings {
    width: 100%;
  }
  
  .visual-condition, .visual-action {
    width: 100%;
  }
  
  .condition-row, .action-row {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    margin-bottom: 12px;
    width: 100%;
  }
  
  .condition-fields, .action-fields {
    display: flex;
    flex: 1;
    gap: 12px;
    align-items: center;
    flex-wrap: wrap;
  }
  
  .condition-actions, .action-actions {
    display: flex;
    gap: 8px;
    align-items: center;
    flex-shrink: 0;
    margin-top: 2px;
  }
  
  .field-select, .operator-select, .value-input,
   .type-select, .target-input, .target-select, .params-input, .params-select {
     min-width: 120px;
     flex: 1;
   }
  
  .field-select {
    min-width: 140px;
  }
  
  .operator-select {
    min-width: 100px;
  }
  
  .value-input {
    min-width: 160px;
  }
  
  .type-select {
    min-width: 120px;
  }
  
  .target-input, .target-select, .params-input, .params-select {
     min-width: 150px;
   }
  
  .settings-row {
    width: 100%;
  }
  
  .settings-fields {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    width: 100%;
  }
  
  .inline-form-item {
    margin-bottom: 0;
    flex: 1;
    min-width: 200px;
  }
  
  .frequency-select, .mode-select {
    width: 100%;
    min-width: 150px;
  }
  
  .delay-input, .retry-input, .cooldown-input, .max-triggers-input {
    width: 100%;
  }
  
  .el-tabs {
    width: 100%;
  }
  
  .el-collapse {
    width: 100%;
  }
  
  .el-collapse-item {
    width: 100%;
  }
  
  .el-textarea {
    width: 100%;
  }
  
  @media (max-width: 768px) {
    .condition-row, .action-row {
      flex-direction: column;
      align-items: stretch;
    }
    
    .condition-fields, .action-fields {
      flex-direction: column;
      gap: 8px;
    }
    
    .condition-actions, .action-actions {
      justify-content: flex-start;
      margin-top: 8px;
    }
    
    .settings-fields {
      flex-direction: column;
      gap: 16px;
    }
    
    .inline-form-item {
      min-width: auto;
    }
  }
}

.condition-editor,
.action-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
}

.visual-condition,
.visual-action {
  min-height: 60px;
}

.visual-condition .el-row,
.visual-action .el-row {
  margin-bottom: 10px;
  align-items: center;
}

.visual-condition .el-row:last-child,
.visual-action .el-row:last-child {
  margin-bottom: 0;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-collapse-item__header) {
  font-size: 14px;
  font-weight: 500;
}

:deep(.el-tabs__item) {
  font-size: 13px;
}
</style>